var ex = require('express');
var commentdao = require(process.env.ROOT +'/model/commentdao.js');
var qs = require('querystring');
var router = ex.Router();


//商品详情显示的时候 查寻所有评论信息
router.post('/selectCommentByGoodsId',function(req,res,next){
		var alldata='';
		req.addListener('data',function(chunk){
			alldata+=chunk;
		});
		req.addListener('end',function(){
			var dataObj = qs.parse(alldata);
			//console.log('==========='+dataObj.goods_id_detail);
			var query = commentdao.Comment.find({goods_id:dataObj.goods_id_detail});
			query.exec(function (err, docs) {
				if(err){
						console.log("err="+err);
						res.end("1");
				}else{
					//console.log('docs'+docs);
					res.end(JSON.stringify(docs));
				}
			});
		});
});

//添加评论
router.post('/addComment',function(req,res){
		var alldata='';
		req.addListener('data',function(chunk){
			alldata+=chunk;
		});
		req.addListener('end',function(){
			var dataObj = qs.parse(alldata);
			//console.log(dataObj.comment_text+'==========='+dataObj.goods_id_detail);
			//console.log(req.session.user);
			
			//说明用户没有登录 返回错误码  重新登录
			if(req.session.user == null || req.session.user==''  ){
				res.end('1');//用户没有登录 返回错误码1  重新登录		
			}else{
				//获取用户登录的用户名
				var user_name = req.session.user;
				//存储数据
				var comment = new commentdao.Comment({
					goods_id: dataObj.goods_id_detail,
					user_name: user_name,
					comment_text: dataObj.comment_text	
				})
				//保存数据库
				comment.save(function(err) {
					if (err) {
						console.log('保存失败');
						res.end('1');
						return;
					}else{
						res.end('2');
					}
				});	
			}
		});
});


//回复评论
router.post('/doAnwserCommentByCommentId',function(req,res){
	
		var alldata='';
		req.addListener('data',function(chunk){
			alldata+=chunk;
		});
		req.addListener('end',function(){
			var dataObj = qs.parse(alldata);
			//console.log(dataObj.comment_text+'==========='+dataObj.comment_id+'==========='+dataObj.goods_id_detail);
			//console.log(req.session.user);
			
			//说明用户没有登录 返回错误码  重新登录
			if(req.session.user == null || req.session.user==''  ){
				res.end('3');//用户没有登录 返回错误码3  重新登录		
			}else{
				//获取用户登录的用户名
				var user_name = req.session.user;
				//存储数据
				var comment = new commentdao.Comment({
					goods_id: dataObj.goods_id_detail,
					user_name: user_name,
					comment_text: dataObj.comment_text	
				})
				commentdao.Comment.update({'_id': dataObj.comment_id}, {
					$push:{"comments":{comment}}
				}, function(err) {
					if(err){
						console.log(err);
						res.end('1');
						return
					}else{
						console.log('更新成功')
						res.end('2');
					}
					
				});
			}	
		});
});


module.exports = router;
